#include "texture.h"
#include "canvas.h"
#include "image_file.h"
#include <cassert>

using namespace krryn::view;

texture::texture(const std::string &a_Filename)
: m_Filename(a_Filename) {load();}

GLuint texture::get_id(){return m_TextureId;}

texture::~texture(){
	glDeleteTextures(1, &m_TextureId);
}

int texture::get_width() const{
	return m_Width;
}

int texture::get_height() const{
	return m_Height;
}

int texture::get_pitch() const{
	return m_Pitch;
}

void texture::load(){
	image_file_bmp l_Bmp(m_Filename);

	view::canvas *l_Canvas = l_Bmp.load();

	m_Width = l_Canvas->get_width();
	m_Height = l_Canvas->get_height();
	m_Pitch = l_Canvas->get_pitch();

	glGenTextures(1, &m_TextureId);
	glBindTexture(GL_TEXTURE_2D, m_TextureId);

	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

	GLuint l_Error = gluBuild2DMipmaps(
		GL_TEXTURE_2D, 4,
		l_Canvas->get_width(),
		l_Canvas->get_height(),
		GL_RGBA,
		GL_UNSIGNED_BYTE,
		(GLubyte*)l_Canvas->get_buffer()
	);

	assert(l_Error == 0);
}
